package com.cabal.common.sms;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cabal.common.sms.http.*;
import com.cabal.common.sms.request.SmsSingleRequest;
import com.cabal.common.sms.response.SmsInternationalResp;
import com.cabal.common.sms.response.SmsResponse;
import com.cabal.common.util.HttpClientUtil;
import lombok.extern.slf4j.Slf4j;


import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;

/**
 * 短信发送工具类
 *
 * @author shenkang
 * @data 2022年4月25日
 */
@Slf4j
public class SmsSendUtil {

    // appId
    static String appId = "EUCP-EMY-SMS1-1IW8D";
    // 密钥
    static String secretKey = "DC6676D46511C304";
    // 接口地址
    static String host = "http://bjmtn.b2m.cn:80";
    // 加密算法
    static String algorithm = "AES/ECB/PKCS5Padding";
    // 编码
    static String encode = "UTF-8";
    // 是否压缩
    static boolean isGizp = true;

    static String internationalUrl = "http://intapi.253.com/mt";

    static String internationalAppkey = "I043411_I4582828";

    static String internationalSecret = "SiTV0BIDpHf273";

    public static boolean sendSms(String logisticsNo,String mobile,String name){
        return setSingleSms(appId, secretKey, host, algorithm, "【Apollo数字清关】"+logisticsNo+"尊敬的"+name+"客户，您好！根据中国海关规定您的包裹清关需要上传身份证照片，麻烦您尽快到我司微信公众号“Apollo数字清关”进行身份证上传，如无法及时上传，您的包裹可能滞留海外无法飞往中国，谢谢", null, null, mobile, isGizp, encode,name);

    }

    public static void main(String[] args) {
        sendSmsVerifyNum("8619988880018","【数字清关】尊敬的用户，您好！您的密码为：Apollo123456");
    }

    /**
     * 微信公众号发送短信验证码
     *
     * @return
     */
    public static boolean sendSmsVerifyCode(String verifyCode,String mobile){
        return setSingleSms(appId, secretKey, host, algorithm, "【Apollo公众号】尊敬的用户，您好！您的验证码为："+verifyCode, null, null, mobile, isGizp, encode,null);

    }

    /**
     *Apollo平台短信验证码发送
     */
    public static boolean sendSmsVerifyNum(String mobile,String content){
        return setSingleSms(appId, secretKey, host, algorithm, content, null, null, mobile, isGizp, encode,null);

    }

    /**
     * 国际短信
     * @param phone
     * @return
     */
    public static   String sendInternationalCode(String  phone,String content ){
        // 短信内容
        try {
            content = URLEncoder.encode(content, "utf-8");
        } catch (UnsupportedEncodingException e) {
            log.error(e.getMessage());
            return null;
        }
        StringBuffer strBuf = new StringBuffer(internationalUrl);
        strBuf.append("?un=").append(internationalAppkey);
        strBuf.append("&pw=").append(internationalSecret);
        strBuf.append("&da=").append(phone);
        strBuf.append("&sm=").append(content);
        strBuf.append("&dc=15&rd=1&rf=2&tf=3");
        log.info("国际短信验证请求参数:"+strBuf);
        String resStr= HttpClientUtil.doGet(strBuf.toString(),null);
        log.info("国际短信验证响应参数:"+resStr);
        SmsInternationalResp smsInternationalResp=null;
        if(resStr!=null){
            smsInternationalResp= JSONObject.parseObject(resStr, SmsInternationalResp.class);
            //成功后返回验证码
            if(smsInternationalResp.getSuccess()){
                return "发送成功";
            }
        }
        return "发送失败";
    }

    /**
     * 单个短信发送
     *
     * @param appId
     * @param secretKey
     * @param host
     * @param algorithm
     * @param content
     * @param customSmsId
     * @param extendCode
     * @param mobile
     * @param isGzip
     * @param encode
     */
    private static boolean setSingleSms(String appId, String secretKey, String host, String algorithm, String content, String customSmsId, String extendCode, String mobile, boolean isGzip, String encode,String name) {
        log.info("=============begin setSingleSms==================");
        SmsSingleRequest pamars = new SmsSingleRequest();
        pamars.setContent(content);
        pamars.setCustomSmsId(customSmsId);
        pamars.setExtendedCode(extendCode);
        pamars.setMobile(mobile);
        ResultModel result = request(appId, secretKey, algorithm, pamars, host + "/inter/sendSingleSMS", isGzip, encode);
        log.info("result code :" + result.getCode());
        if ("SUCCESS".equals(result.getCode())) {
            SmsResponse response = JsonHelper.fromJson(SmsResponse.class, result.getResult());
            if (response != null) {
                log.info("data : " + response.getMobile() + "," + response.getSmsId() + "," + response.getCustomSmsId());
            }
            return true;
        }
        log.info("=============end setSingleSms==================");
        return false;
    }


    /**
     * 公共请求方法
     */
    public static ResultModel request(String appId, String secretKey, String algorithm, Object content, String url, final boolean isGzip, String encode) {
        Map<String, String> headers = new HashMap<String, String>();
        HttpRequest<byte[]> request = null;
        try {
            headers.put("appId", appId);
            headers.put("encode", encode);
            String requestJson = JsonHelper.toJsonString(content);
            log.info("result json: " + requestJson);
            byte[] bytes = requestJson.getBytes(encode);
            log.info("request data size : " + bytes.length);
            if (isGzip) {
                headers.put("gzip", "on");
                bytes = GZIPUtils.compress(bytes);
                log.info("request data size [com]: " + bytes.length);
            }
            byte[] parambytes = AES.encrypt(bytes, secretKey.getBytes(), algorithm);
            log.info("request data size [en] : " + parambytes.length);
            HttpRequestParams<byte[]> params = new HttpRequestParams<byte[]>();
            params.setCharSet("UTF-8");
            params.setMethod("POST");
            params.setHeaders(headers);
            params.setParams(parambytes);
            params.setUrl(url);
            if (url.startsWith("https://")) {
                request = new HttpsRequestBytes(params, null);
            } else {
                request = new HttpRequestBytes(params);
            }
        } catch (Exception e) {
            log.info("加密异常:"+e.getMessage());
        }
        HttpClient client = new HttpClient();
        String code = null;
        String result = null;
        try {
            HttpResponseBytes res = client.service(request, new HttpResponseBytesPraser());
            if (res == null) {
                log.info("请求接口异常");
                return new ResultModel(code, result);
            }
            if (res.getResultCode().equals(HttpResultCode.SUCCESS)) {
                if (res.getHttpCode() == 200) {
                    log.info("HttpResponseBytes : " + JSON.toJSONString(res));
                    code = res.getHeaders().get("result");
                    if (code.equals("SUCCESS")) {
                        byte[] data = res.getResult();
                        log.info("response data size [en and com] : " + data.length);
                        data = AES.decrypt(data, secretKey.getBytes(), algorithm);
                        if (isGzip) {
                            data = GZIPUtils.decompress(data);
                        }
                        log.info("response data size : " + data.length);
                        result = new String(data, encode);
                        log.info("response json: " + result);
                    }
                } else {
                    log.info("请求接口异常,请求码:" + res.getHttpCode());
                }
            } else {
                log.info("请求接口网络异常:" + res.getResultCode().getCode());
            }
        } catch (Exception e) {
            log.info("解析失败:"+e.getMessage());
        }
        ResultModel re = new ResultModel(code, result);
        return re;
    }
}
